package com.zlx.mall.basic.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.setting.dialect.Props;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xiatian
 * @Date 2024/5/27 星期一 16:26
 * @注释
 */
public class JwtUtils {

    private static final Logger LOG = LoggerFactory.getLogger(JwtUtils.class);
    public static final String PAYLOAD_USER_ID = "userId";
    public static final String PAYLOAD_MOBILE = "mobile";

    /**
     * 盐值很重要，不能泄漏，且每个项目都应该不一样，可以放到配置文件中
     */
    private static final String KEY = "zlx_token_salt";
    /**
     * token过期时间：默认24小时
     */
    @Value("${hzl.app.biz.token.expire:24}")
    private Integer tokenExpire;

    /**
     * 创建token
     * @return
     */
    public static String createToken(Long userId, String mobile) {
        DateTime now = DateTime.now();
        Map<String, Object> payload = new HashMap<>();
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间默认 24小时
        Props props = new Props("application.properties", CharsetUtil.CHARSET_UTF_8);
        Integer tokenExpire = props.getInt("hzl.app.biz.token.expire");
        if (null == tokenExpire) {
            tokenExpire = 24;
        }
        payload.put(JWTPayload.EXPIRES_AT, DateUtil.offsetDay(now, tokenExpire));
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        // 内容
        payload.put(PAYLOAD_USER_ID, userId);
        payload.put(PAYLOAD_MOBILE, mobile);
        String token = JWTUtil.createToken(payload, KEY.getBytes());
        LOG.info("生成JWT token：{}", token);
        return token;
    }

    public static JWT parse(String token) {
        return JWTUtil.parseToken(token).setKey(KEY.getBytes());
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean validate(String token) {
        JWT jwt = parse(token);
        // validate包含了verify
        boolean validate = jwt.validate(0);
        LOG.info("JWT token校验结果：{}", validate);
        return validate;
    }

    public static JSONObject getJSONObject(String token) {
        JWT jwt = parse(token);
        JSONObject payloads = jwt.getPayloads();
        payloads.remove(JWTPayload.ISSUED_AT);
        payloads.remove(JWTPayload.EXPIRES_AT);
        payloads.remove(JWTPayload.NOT_BEFORE);
        LOG.info("根据token获取原始内容：{}", payloads);
        return payloads;
    }

    public static void main(String[] args) {
        String token = createToken(1L, "15563285722");

        //String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE2NzY4OTk4MjcsIm1vYmlsZSI6IjEyMyIsImlkIjoxLCJleHAiOjE2NzY4OTk4MzcsImlhdCI6MTY3Njg5OTgyN30.JbFfdeNHhxKhAeag63kifw9pgYhnNXISJM5bL6hM8eU";
        validate(token);
        JWT jwt = JWTUtil.parseToken(token);
        JSONObject payloads = jwt.getPayloads();
        String mobile = payloads.getStr("mobile");
        getJSONObject(token);

        DateTime expTime = DateTime.now().offsetNew(DateField.HOUR, 24);
        System.out.println(expTime);

        System.out.println(DateUtil.tomorrow());
    }
}
